package cn.oi.book.pro.controller;

import cn.oi.book.pro.model.Knowledge;
import cn.oi.book.pro.service.KnowledgeService;
import cn.oi.book.pro.repository.KnowledgeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequiredArgsConstructor
public class HomeController {

    private final KnowledgeService service;
    private final KnowledgeRepository repository;

    @GetMapping("/")
    public String home(@RequestParam(value = "page", defaultValue = "0") int page,
                       @RequestParam(value = "size", defaultValue = "8") int size,
                       Model model) {
        // 默认展示热门/最新文章（从数据库中查）
        Page<Knowledge> result = service.search(null, page, size);
        model.addAttribute("page", result);
        model.addAttribute("isSearch", false);
        return "index";
    }

    @GetMapping("/search")
    public String search(@RequestParam(value = "q", required = false) String q,
                         @RequestParam(value = "page", defaultValue = "0") int page,
                         @RequestParam(value = "size", defaultValue = "10") int size,
                         Model model) {
        Page<Knowledge> result = service.search(q, page, size);
        model.addAttribute("q", q);
        model.addAttribute("page", result);
        model.addAttribute("isSearch", true);
        return "index";
    }

    @GetMapping("/article/{id}")
    public String detail(@PathVariable Long id, Model model) {
        Knowledge k = service.findById(id).orElse(null);
        model.addAttribute("item", k);
        if (k != null) {
            java.util.List<Knowledge> related;
            if (k.getCategory() != null && !k.getCategory().isBlank()) {
                related = repository.findTop5ByCategoryAndIdNotOrderByUpdatedAtDesc(k.getCategory(), k.getId());
            } else {
                related = repository.findTop5ByIdNotOrderByUpdatedAtDesc(k.getId());
            }
            model.addAttribute("related", related);
        }
        return "article_view";
    }

    @GetMapping("/search/fragment")
    public String searchFragment(@RequestParam(value = "q", required = false) String q,
                                 @RequestParam(value = "page", defaultValue = "0") int page,
                                 @RequestParam(value = "size", defaultValue = "10") int size,
                                 Model model) {
        Page<Knowledge> result = service.search(q, page, size);
        model.addAttribute("q", q);
        model.addAttribute("page", result);
        return "fragments/search_results";
    }
}
